package com.android.svmc.app.mobile.activity;

import java.util.ArrayList;

import luyenlv.pro.screen.base.BaseActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.svmc.app.mobile.adapter.ListPostInCategoryAdapter;
import com.android.svmc.app.mobile.controller.WifiManagement;
import com.android.svmc.app.mobile.data.DatabaseSource;
import com.android.svmc.app.mobile.data.JsonData;
import com.android.svmc.app.mobile.model.PostDetail;
import com.android.svmc.app.mobile.tabmanager.TabGroupActivity;
import com.android.svmc.app.mobile.util.CommonDefine;
import com.android.svmc.app.mobile.util.SettingUtils;
import com.android.svmc.app.mobile.view.FontTextView;

public class ListPostInCategory extends BaseActivity implements
		OnClickListener, CommonDefine {
	private ListView ls;
	private int id_category;
	private String title_category;
	private ArrayList<PostDetail> listpost = new ArrayList<PostDetail>();
	private ArrayList<PostDetail> theFirstList = new ArrayList<PostDetail>();
	private TextView title;
	private TextView emtry_data;
	private int page = 1;
	private ListPostInCategoryAdapter myadapter;
	private TabGroupActivity parentActivity;
	private RelativeLayout rl_listpost_loading;
	private firstlistPost fistpost;
	private nextlistPost nextpost;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(getLayout(R.array.listpostincategory_layout));
		//setContentView(R.layout.listpostincategory_320);
		parentActivity =(TabGroupActivity)getParent();
		initUI();
		setclicklistener();
		/*************************************
		 *  Get Data From MainMenu
		 ************************************/
		Bundle data = getIntent().getExtras();
		id_category = data.getInt(ID_CATEGORY);
		title_category = data.getString(TITLE);
		title.setText(title_category);
		filldata();
		/***********************************/

	}
	private void initUI(){
		ls = (ListView) findViewById(R.id.listpost_listview);
		title = (TextView) findViewById(R.id.listpost_titlebar_txt_title);
		ls.setVisibility(View.GONE);
		/********************************************
		 * Add Footer load More
		 ********************************************/
		View footerView = getLayoutInflater().inflate(R.layout.footer_load_more, ls, false);
		Button loadmorebtn = (Button) footerView.findViewById(R.id.footer_btn_loadmore);
		loadmorebtn.setOnClickListener(this);
		ls.addFooterView(footerView);
		/********************************************/
		WifiManagement.getInstance(getApplicationContext());
		/***********************************
		 *  add header
		 ***********************************/
		rl_listpost_loading = (RelativeLayout)findViewById(R.id.list_all_post_rl_loading);
		rl_listpost_loading.setVisibility(View.GONE);
		TextView loading = (TextView)findViewById(R.id.header_listview_listpost_txt_loading);
		FontTextView.setfontMyriadPro_semiBold(loading, this);
		
		emtry_data = (TextView)findViewById(R.id.listpost_txt_emtry);
		emtry_data.setVisibility(View.GONE);
		
		Log.i("anhson", "oncreat() Listpost");
	}
	private void setclicklistener(){
		findViewById(R.id.listpost_btn_back).setOnClickListener(this);
		findViewById(R.id.listpost_btn_reload).setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.i("anhson", "onResume() Listpost");
		ls.requestFocus();
	}

	private void filldata() {

		if (WifiManagement.haveNetworkConnection() ==true){
			fistpost = new firstlistPost();
			fistpost.execute();
		}else if (SettingUtils.getbooleanPreferences(this, IS_OFFLINE_MODE)==true) {
			DatabaseSource db = new DatabaseSource(this);
			listpost = db.getPostbyCategory(id_category);
			Log.i(TAG, "listpost " +listpost.size());
			if (myadapter == null) {
				myadapter = new ListPostInCategoryAdapter(
						ListPostInCategory.this, listpost,
						WifiManagement.haveNetworkConnection());
				if (ls != null && myadapter != null) {
					ls.setAdapter(myadapter);
					myadapter.notifyDataSetChanged();
				}
			}
			if (listpost.size() != 0){
				ls.setVisibility(View.VISIBLE);
			}else {
				emtry_data.setVisibility(View.VISIBLE);
			}
			
		}
		
		listenClickListView(ls);
	}

	public class firstlistPost extends AsyncTask<Void, Void, Void> {
		ArrayList<PostDetail> list;

		@Override
		protected Void doInBackground(Void... arg0) {

			JsonData json = new JsonData(ListPostInCategory.this);
			theFirstList = json.getAllPost(id_category, 1);
			if (theFirstList.size() != 0 && theFirstList != null
					&& listpost.size() == 0) {
				for (PostDetail post : theFirstList) {
					listpost.add(post);
				}
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			ls.setPadding(0, 0, 0, 0);
			rl_listpost_loading.setVisibility(View.GONE);
			if (theFirstList.size() != 0 && theFirstList != null) {
				if (myadapter == null) {
					myadapter = new ListPostInCategoryAdapter(
							ListPostInCategory.this, theFirstList,
							WifiManagement.haveNetworkConnection());
				}
			}
			if (theFirstList != null) {
				if (ls != null && myadapter != null) {
					ls.setAdapter(myadapter);
					myadapter.notifyDataSetChanged();
					myadapter.notifyDataSetInvalidated();
				}

			}

			if (theFirstList.size() != 0) {
				if (ls != null) {
					ls.setVisibility(View.VISIBLE);
				}

			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			rl_listpost_loading.setVisibility(View.VISIBLE);
			ls.setPadding(0, 30, 0, 0);
		}
	}

	public class nextlistPost extends AsyncTask<Void, Void, Void> {
		ProgressDialog dialog;
		ArrayList<PostDetail> list;

		@Override
		protected Void doInBackground(Void... arg0) {
			page++;
			JsonData json = new JsonData(ListPostInCategory.this);
			list = json.getAllPost(id_category, page);
			if (listpost != null || list != null) {
				listpost.addAll(list);
			} else {
				listpost = list;
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			ls.setPadding(0, 0, 0, 0);
			rl_listpost_loading.setVisibility(View.GONE);
			if (listpost != null) {
				myadapter = new ListPostInCategoryAdapter(
						ListPostInCategory.this, listpost,
						WifiManagement.haveNetworkConnection());
			}
			if (listpost != null) {
				int currentPosition = ls.getFirstVisiblePosition();
				ls.setAdapter(myadapter);
				myadapter.notifyDataSetChanged();
				myadapter.notifyDataSetInvalidated();
				ls.setSelectionFromTop(currentPosition + 1, 0);
			}
			if (listpost.size() != 0) {
				ls.setVisibility(View.VISIBLE);
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			rl_listpost_loading.setVisibility(View.VISIBLE);
			ls.setPadding(0, 30, 0, 0);
		}
	}

	public void listenClickListView(ListView listview) {
		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position,
					long id) {
				Intent out = new Intent(ListPostInCategory.this, DetailPostActivity.class);
				out.putExtra(ID_ACTIVITY, POST_ACTIVITY);
				out.putExtra(ID_POST, listpost.get(position).getId());
				out.putExtra(TITLE, listpost.get(position).getSubtitle());
				parentActivity.startChildActivity("DetailPostActivity", out);
			}
			
		});
	}

	/**
	 * Get context in groupActivity.Use for show dialog
	 * 
	 * @return : context
	 */
	private Context getDialogContext() {
		Context mcontext;
		if (getParent() != null)
			mcontext = getParent();
		else
			mcontext = this;
		return mcontext;
	}

	@Override
	public void clearMemory() {
		unbindReferences(this, R.id.listpost_rl);

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if ( fistpost !=null && !fistpost.isCancelled()){
			fistpost.cancel(true);
		}
		if(nextpost !=null && !nextpost.isCancelled()){
			nextpost.cancel(true);
		}

		ls = null;
		title = null;
		myadapter = null;
		System.gc();
		
		Log.i("anhson", "onDestroy() Listpost");
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.listpost_btn_back:
			this.finish();
			break;
		case R.id.footer_btn_loadmore:
			if (WifiManagement.haveNetworkConnection()) {
				nextpost = new nextlistPost();
				nextpost.execute();
			} else {
				Toast.makeText(this,
						getString(R.string.label_dialog_info_network), 0)
						.show();
			}
			break;
		case R.id.listpost_btn_reload:
			if(WifiManagement.haveNetworkConnection()==true){
				fistpost = new firstlistPost();
				fistpost.execute();
			}else {
				Toast.makeText(this, getString(R.string.label_dialog_info_network), 0).show();
			}
			
			break;
		default:
			break;
		}
	}

}
